package com.cms.recursoshumanos.activity.user.familiar;

//import java.lang.ref.WeakReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import com.example.frontendrecursoshumanos.R;
import com.cms.recursoshumanos.activity.main.MainRecursosHumanosActivity;
import com.cms.recursoshumanos.cache.UserInfoCache;
import com.cms.recursoshumanos.constant.Constant;
import com.cms.recursoshumanos.handler.ImagenesHandler;
import com.cms.recursoshumanos.handler.ListaFamiliarActivityHandler;
import com.cms.recursoshumanos.object.Familiar;
import com.cms.recursoshumanos.object.Persona;
import com.cms.recursoshumanos.object.Usuario;
import com.cms.recursoshumanos.object.list.ListaFamiliar;
import com.cms.recursoshumanos.utilities.Tool;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ListaFamiliarActicity extends MainRecursosHumanosActivity 
{

	private static FamiliarAdapter adaptador;
	
	protected static ListaFamiliarAsync asyncListaFamiliarTask;
	
	private static ListView listViewFamiliar;
	private static TextView cantidad_listado;
	private static EditText buscador;

	private static ListaFamiliar listado;
	private static Usuario elUsuario;
	
	private ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lista_familiar);
		elUsuario = UserInfoCache.getInstance().getUsuario();
		listado = UserInfoCache.getInstance().getListaFamiliar();
		setCompenents();
	}
	@Override
	protected void onResume() 
	{
		super.onResume();
		if (listado == null)
		{
			listado = UserInfoCache.getInstance().getListaFamiliar();
		}
		if (elUsuario == null)
		{
			elUsuario = UserInfoCache.getInstance().getUsuario();
		}
	}

	public void goDetailFamiliar(Familiar elFamiliar)
	{
		Intent intent = new Intent(ListaFamiliarActicity.this, DetailFamiliarActivity.class);
		
		Bundle bundle = new Bundle();
		bundle.putString("id_familiar", ""+ elFamiliar.getIdFamiliar());
		intent.putExtras(bundle);
		
		startActivity(intent);
	}
	public void onRefreshClick(View v)
	{
		findListaFamiliar();
	}
	public void findListaFamiliar()
	{
		asyncListaFamiliarTask = new ListaFamiliarAsync(elUsuario);
		asyncListaFamiliarTask.execute();

	}
	public void refresh_lista()
	{
		listado = UserInfoCache.getInstance().getListaFamiliar();
		setListadoCompleto();
	}
	public void setCompenents()
	{
		
		listViewFamiliar =  (ListView)  findViewById ( R.id.lvFamiliar );
		cantidad_listado = (TextView) /*layout_cantidad.*/findViewById(R.id.tvCantidadFamiliar);
		buscador = (EditText) findViewById(R.id.etSearch);
		
		buscador.addTextChangedListener(new TextWatcher() 
		{

			   public void afterTextChanged(Editable s)
			   {
			   }

			   public void beforeTextChanged(CharSequence s, int start, int count, int after) 
			   {

			   }

			   public void onTextChanged(CharSequence s, int start, int before, int count) 
			   {
				   
				   int textlength = buscador.getText().length();
				   
				   if (textlength == 0)
				   {
					   setListadoCompleto();
				   }
				   else
				   {
					   setListadoParam();
				   }

			   }
		});
		setListadoCompleto();
		
		
		
		
	}
	public void setListadoCompleto()
	{
		cantidad_listado.setText("Se encontraron "+listado.cantElementListaFamiliar()+" registro(s).");
		adaptador = new FamiliarAdapter(this, listado.getListaFamiliar());
		listViewFamiliar.setAdapter(adaptador);
	}
	public void setListadoParam()
	{
		int textlength = buscador.getText().length();
		List<Familiar> listado_familiar_mostrar = new ArrayList<Familiar>();
		   
		for (int i = 0; i < listado.cantElementListaFamiliar(); i++) 
		{
			Familiar familiar_aux = listado.getFamiliarAtIndex(i);
	   
			String nombre_familiar = familiar_aux.getPersona().getApellido_Persona_1()+" "
										+familiar_aux.getPersona().getNombre_Persona_1();
	   
			if (textlength <= nombre_familiar.length()) 
			{
				if (buscador.getText().toString().equalsIgnoreCase(  (String) nombre_familiar.subSequence(0,textlength))) 
				{
					listado_familiar_mostrar.add(familiar_aux);
				}
			}
		}
		
		
		cantidad_listado.setText("Se encontraron "+listado_familiar_mostrar.size()+" registro(s).");
		adaptador = new FamiliarAdapter(this, listado_familiar_mostrar);
		listViewFamiliar.setAdapter(adaptador);
	}
	public class FamiliarAdapter extends ArrayAdapter<Familiar> 
	{
	    LayoutInflater mInflater ;  
	    private List<Familiar> mItems ;
	    private ViewHolder holder;
	 
	    public FamiliarAdapter  ( Context context , List<Familiar> items)  
	    {
	        super ( context, -1, items )  ;
	        this.mItems = items ;
	        this.mInflater = LayoutInflater.from(context) ;
	    }
	    
	    @ Override
	    public View getView ( final int position, View convertView, ViewGroup parent )  
	    {
	            // Inflate the custom view
	    	//View v = listViewFamiliar.getChildAt(position - listViewFamiliar.getFirstVisiblePosition());//convertView;
	    	convertView =   mInflater.inflate( R.layout.elementos_lista_objeto_imagen_item,null);    		
    		convertView.setOnClickListener(new OnClickListener() 
    		{
				
				@Override
				public void onClick(View v) 
				{
					goDetailFamiliar(mItems.get(position));
				}
			});
	    	/*if ( convertView == null)
    		{
	    		
	    		
    		}*/
	    	
	    	if (convertView.getTag() == null)
	    	{
	    		holder = new ViewHolder();
	    		
	    		holder.detallePersona = (TextView) convertView.findViewById(R.id.tvNombreDetalle);
	    		holder.nombrePersona = (TextView) convertView.findViewById(R.id.tvNombrePrincipal);
	    		holder.imagen_foto = (ImageView) convertView.findViewById(R.id.ivFotoObjeto);
	    		holder.progreso = (ProgressBar) convertView.findViewById(R.id.pBImagen);
	    		holder.flag_buscar = true;

	    	}
	    	else
	    	{
	    		holder = (ViewHolder) convertView.getTag();
	    	}
    		
	    	
    		
    		holder.nombrePersona.setText(mItems.get(position).getPersona().getApellido_Persona_1() +", "+
    								mItems.get(position).getPersona().getNombre_Persona_1());
    		holder.detallePersona.setText(mItems.get(position).getParentesco().getNombreParentesco());
    		
    		holder.progreso.setVisibility(View.VISIBLE);
			holder.imagen_foto.setVisibility(View.GONE);
    		
			if (holder.imagen_foto != null)
			{
				if (mItems.get(position).getPersona().getFoto_Persona() == null)
				{
					if (holder.flag_buscar) 
					{
						holder.flag_buscar = false;
						new DownloadImageTask(ListaFamiliarActicity.this).execute(position);
					}
				}
				else
				{
					holder.imagen_foto.setVisibility(View.VISIBLE);
					holder.progreso.setVisibility(View.GONE);
					holder.imagen_foto.setImageBitmap(mItems.get(position).getPersona().getFoto_Persona());
				}
			}
			convertView.setTag(holder);
	        return convertView ;
	    }
	    private class ViewHolder 
	    {    	  
    		TextView detallePersona;
    		TextView nombrePersona;
    		ImageView imagen_foto;
    		ProgressBar progreso;
    		boolean flag_buscar;
    		
        }
	}
	private class ListaFamiliarAsync extends AsyncTask<String, Void, String>
	{
		private Usuario elUsuario;
		public  ListaFamiliarAsync(Usuario elUsuario)
	    {
			this.elUsuario = elUsuario;
	    }
		@SuppressWarnings("deprecation")
		@Override
		protected void onPreExecute()
		{
			showDialog(0);
			dialog = ProgressDialog.show(ListaFamiliarActicity.this, "Espere","Cargando...",true );
		}
	
		@Override
		protected String doInBackground(String... arg0) 
		{
			ListaFamiliarActivityHandler handler = new ListaFamiliarActivityHandler();
			String result = handler.refreshListaFamiliar(elUsuario.getNombre_Usuario(),
															elUsuario.getPassword());
			return result;
		}
		
		@Override
		public void onPostExecute(String  result)
		{
			
			String str_result = result;
			
			if (str_result.equals(Constant.CODE_OK))
			{	
				Tool.getInstance().saveUserInfoShared(4,UserInfoCache.getInstance().getListaFamiliar());
				refresh_lista();
			}
			else 
			{
				Tool.getInstance().showMessage(str_result);
			}
			dialog.cancel();
			this.cancel(true);
			
			
		}
		
	}
	private class DownloadImageTask extends AsyncTask<Integer, Void, Bitmap> 
	{
		
		WeakReference<ListaFamiliarActicity> context;
		@SuppressWarnings("unused")
		ListaFamiliarActicity activity;
		int index;
	 
		public DownloadImageTask(ListaFamiliarActicity activity) 
		{	
			context = new WeakReference<ListaFamiliarActicity>(activity);
			this.activity = context.get();
		}
		@SuppressWarnings("deprecation")
		@Override
		protected void onPreExecute()
		{
			showDialog(0);
			//dialog = ProgressDialog.show(ListaFamiliarActicity.this, "Espere","Cargando...",true );
		}
		@Override
		protected Bitmap doInBackground(Integer... position) 
		{
			index = position[0];        	
			ImagenesHandler handler = new ImagenesHandler();
			Persona laPersonaAux = (adaptador.getItem(index)).getPersona();
			return handler.GetImage(laPersonaAux.getUrlFoto());
		}
		
		@Override
		protected void onPostExecute(Bitmap poster) 
		{  
			View itemView = null;
			ImageView itetmImageView = null;
			int index_list_v = listViewFamiliar.getFirstVisiblePosition();
			int index_real = index - index_list_v;
			Familiar elFamiliar = listado.getFamiliarAtIndex(index);
	        //agarra el listview y me devuelve el item en una posicion donde se encuentra
	        if(listViewFamiliar != null)
	        {
        		itemView = listViewFamiliar.getChildAt(index_real);
	        }
	        
	        if (poster == null)
	        {
	        	poster = BitmapFactory.decodeResource(MainRecursosHumanosActivity.getAppContext().getResources(), R.drawable.avatar_blank);
	        }
	        
	        if (itemView != null)
	        {
	        	itetmImageView = (ImageView) itemView.findViewById(R.id.ivFotoObjeto);
	        	if (itetmImageView != null)
	        	{
        			itetmImageView.setVisibility(View.VISIBLE);
	        		if(poster != null)
		        	{
	        			((ProgressBar) itemView.findViewById(R.id.pBImagen)).setVisibility(View.INVISIBLE);
	        			itetmImageView.setImageBitmap(poster);
	        			elFamiliar.getPersona().setFoto_Persona(poster);
	        			listado.actualizarFamiliar(elFamiliar);
	        			UserInfoCache.getInstance().getListaFamiliar().actualizarFamiliar(elFamiliar);
	        				
		        	}
	        	}
	        }
		}
    }
	
}
